$(function(){
	var param = $("#tabContent > .tab-pane.active").data(); //获取上级页面的参数
	paramTabPage[tabId] = jQuery.extend(true, {}, param);
	$("[role='tabpanel']").each(function(i,n){
		$(n).addClass('testCon');
	});
	var quotas = [{code: "InCaseCnt", name:"入组病例数",isLink:"1"}, 
	              {code:"CMI", name:"CMI值",isLink:"0"}, {code:"DRGCount", name:"DRGs组数",isLink:"0"}, 
	              {code: "TimeEff", name:"时间消耗指数",isLink:"0"}, {code: "FeeEff", name:"费用消耗指数",isLink:"0"}
	              ];
	var depQuotas = [{code: "InCaseCnt", name:"入组病例数",isLink:"1"}, 
	              {code:"CMI", name:"CMI值",isLink:"0"}, 
	              {
						code : "CMIcc",
						name : (param.compareType == 'manage' ? "CMI值[绩效]"
								: (param.compareType == 'std' ? "CMI值[标杆]"
										: "CMI值[院内均值]")),
						value: param.typeOne,
						isLink : "0"
					},
	              {code:"DRGCount", name:"DRGs组数",isLink:"0"}, 
	              {
						code : "DRGCountcc",
						name : (param.compareType == 'manage' ? "DRGs组数[绩效]"
								: (param.compareType == 'std' ? "DRGs组数[标杆]"
										: "DRGs组数[院内均值]")),
						value: param.typeTwo,
						isLink : "0"
					},
	              {code: "TimeEff", name:"时间消耗指数",isLink:"0"}, {code: "FeeEff", name:"费用消耗指数",isLink:"0"}
	              ];
	var legend = [param.depName];
	var xdata_1 = [];
	var xdata_2 = [];
	var seriesdata_1 = [];
	var seriesdata_2 = [];
	var ajaxCount = quotas.length*2;
	param.isGetCc = "0";
	getTableData(param, "Base", "dep","hosp", function(data){
		var columns = [];
		var datas = [];
		datas = datas.concat(data);
		concatTableData(depQuotas, datas, "depQuota_CMIDRGCount-table", columns, "dep","hosp", function(table){
			var param_t = drgUI.setAjaxData(tabId);//页面参数
			param_t.monitorType = "dep";
			getTrendData(param_t, "CMI", function(data_0){
				var seriedata_1 = {type: "line",clickable:false, smooth: true, symbol:"none", name: param.depName, data:[]};
				for(o in data_0){
					xdata_1.push(data_0[o].ddesc);
					seriedata_1.data.push(data_0[o].QuotaValue?data_0[o].QuotaValue:0);
				}
				seriesdata_1.push(seriedata_1);
				loadTrendChart("CMI值", xdata_1, seriesdata_1, legend, $("#"+tabId+" #lineChart-1"));
			})
			getTrendData(param_t, "DRGCount", function(data_1){
				var seriedata_2 = {type: "line",clickable:false, smooth: true, symbol:"none", name: param.depName, data:[]};
				for(o in data_1){
					xdata_2.push(data_1[o].ddesc);
					seriedata_2.data.push(data_1[o].QuotaValue?data_1[o].QuotaValue:0);
				}
				seriesdata_2.push(seriedata_2);
				loadTrendChart("DRGs组数", xdata_2, seriesdata_2, legend, $("#"+tabId+" #lineChart-2"));
			})
		});
		
	})
	getTableData(param, "Base", "clinic","dep", function(data){
		var columns = [{"data": "ddesc"}];
		var datas = [];
		datas = datas.concat(data);
		concatTableData(quotas, datas, "groupTable-table", columns, "clinic","dep", function(table, oSetting){
			var seriesdata_1_copy = jQuery.extend(true, [], seriesdata_1);
			var seriesdata_2_copy = jQuery.extend(true, [], seriesdata_2);
			var legend_copy = jQuery.extend(true, [], legend);
			var aoData = oSetting.aoData;
			table.find("tbody tr").each(function(i,n){
				$(n).find("td:last a").unbind();
				$(n).find("td:last a").click(function(){
					var rowIndex = $(this).attr("data-rowindex");
					if($("#"+tabId+" #lineChart-1 img").size()>0 || $("#"+tabId+" #lineChart-2 img").size()>0) return;
					if(seriesdata_1_copy.length<=0) seriesdata_1_copy = jQuery.extend(true, [], seriesdata_1);
					if(seriesdata_2_copy.length<=0) seriesdata_2_copy = jQuery.extend(true, [], seriesdata_2);
					var aData = aoData[rowIndex]._aData;
					var ccode = aData.ccode;
					var ddesc=aData.ddesc;
					if($(this).find("i").hasClass("trend-link")){
						$("#"+tabId+" #lineChart-1").html('<img src="images/pageloading.gif" />');
						$("#"+tabId+" #lineChart-2").html('<img src="images/pageloading.gif" />');
						array_remove(legend_copy, ddesc);
						array_removeAttr(seriesdata_1_copy, "name", ccode);
						array_removeAttr(seriesdata_2_copy, "name", ccode);
						loadTrendChart("CMI值", xdata_1, seriesdata_1_copy, legend_copy, $("#"+tabId+" #lineChart-1"));
						loadTrendChart("DRGs组数", xdata_2, seriesdata_2_copy, legend_copy, $("#"+tabId+" #lineChart-2"));
						$(this).find("i").removeClass("trend-link");
					}else{
						$("#"+tabId+" #lineChart-1").html('<img src="images/pageloading.gif" />');
						$("#"+tabId+" #lineChart-2").html('<img src="images/pageloading.gif" />');
						var param_t = drgUI.setAjaxData(tabId);//页面参数
						param_t.monitorType = "clinic";
						param_t.pargroupName = ccode;
						legend_copy.push(ddesc);
						getTrendData(param_t, "CMI", function(data_0){
							var seriedata_avgdays = {type: "line", smooth: true, symbol:"none", name: ccode, data:[]};
							for(o in data_0){
								seriedata_avgdays.data.push(data_0[o].QuotaValue?data_0[o].QuotaValue:0);
							}
							seriesdata_1_copy.push(seriedata_avgdays);
							loadTrendChart("CMI值", xdata_1, seriesdata_1_copy, legend_copy, $("#"+tabId+" #lineChart-1"));
						})
						getTrendData(param_t, "DRGCount", function(data_1){
							var seriedata_1 = {type: "line", smooth: true, symbol:"none", name: ccode, data:[]};
							for(o in data_1){
								seriedata_1.data.push(data_1[o].QuotaValue?data_1[o].QuotaValue:0);
							}
							seriesdata_2_copy.push(seriedata_1);
							loadTrendChart("DRGs组数", xdata_2, seriesdata_2_copy, legend_copy, $("#"+tabId+" #lineChart-2"));
						})
						$(this).find("i").addClass("trend-link");
					}
				})
			})
			table.find("i.trend-link").click();
		});
	})
		
	//添加超链接（病组结构分析） 点击监听事件
	var aHref = $("#"+tabId+"  #disGroupHref a");
	//传递最新的上级页面参数
	var myBingZuJieGouParam = $("#tabContent > .tab-pane.active").data(); 
	//设置要打开的病组结构分析的tab页唯一id值
	var aHrefTabId = 'disGroupAnalysis-'+myBingZuJieGouParam.depCode;
	aHref.unbind("click");
	aHref.bind("click", function(){
		//如果写成 var p =drgUI.setAjaxData(tabId); 则页面始终加载第一次打开时的数据
		var p = myBingZuJieGouParam;
		//父页面科室指标象限分析的tab标题为CMI和DRGs组数---跳转到医政角色病组结构分析页面
		if(p.patientGroupAnalysisPage && p.patientGroupAnalysisPage == 'yizheng'){
			openTab('/pages/yibao/fenxi/disStructureAnalysis.jsp', '病组结构分析'+"|"+p.depName,aHrefTabId, aHrefTabId,p);
		}else if(p.patientGroupAnalysisPage && p.patientGroupAnalysisPage == 'yibao'){
			//父页面科室指标象限分析的其他标题--跳转到医保角色病组结构分析页面
			openTab('/pages/yibao/fenxi/disGroupAnalysis.jsp', '病组结构分析'+"|"+p.depName,aHrefTabId, aHrefTabId,p);
		}
	});
	//
	//将指标与数据拼接成datatables要输出的格式
	function concatTableData(newQuotas, datas, divId, columns, monitorType,specHeader, callback){
		var thead = $("#"+tabId+" #"+divId+" thead tr");
		for(var o in newQuotas){
			var quota = newQuotas[o];
			thead.append("<td>"+quota.name+"</td>");
		}
		var i=0;
		configQuotaFlag(newQuotas[i].code,newQuotas[i].name,i,newQuotas,newQuotas[i].isLink);
		//对非基础指标列进行拼接，用递归方法解决循环与多个ajax请求异步问题
		function configQuotaFlag(value,name,cnt,array,isLink){
			if(value=="CMIcc"||value=="DRGCountcc"){
				columns.push({  "data": value,
								"render": function(obj, type, full){
										if(array[cnt].value==undefined||array[cnt].value==""){
											return "-";
										}else{
											return array[cnt].value;
										}
									}
					});
				if(cnt+1<array.length){
					configQuotaFlag(array[cnt+1].code,array[cnt+1].name,cnt+1,array,array[cnt+1].isLink);
				}
				else return false;
			}else{
				//对有病例明细的列添加链接
				if(isLink=="1"){
					columns.push({ "data": value,
						"type":"number-html",
						"render": function(obj, type, full){	
							if(full[value]=="0"||full[value]==undefined){
								return "0";
							}
							return "<a href=\"javascript:loadCaseDtl('"+full.ddesc+"|"+name+"','"+full.ccode+"','"+monitorType+"', '"+value+"')\">"+(full[value]?full[value]:"")+"</a>";
						}
					});
				}
				else{
					columns.push({ "data": value,
						"render": function(obj, type, full){
							if(full[value]==undefined){
								return "-";

							}else{
								return full[value];
							}
						}});
				}
				getTableData(param, value, monitorType, specHeader,function(data, quotaCode){
					var data_s = [];
					data_s = data_s.concat(data);
					mergeListcc(datas, data_s,'ccode','',quotaCode);
					ajaxCount--;
				})
				if(cnt+1<array.length){
					configQuotaFlag(array[cnt+1].code,array[cnt+1].name,cnt+1,array,array[cnt+1].isLink);
				}
				else return false;
			}
		}
			
		var timer = setInterval(function(){
			if(ajaxCount==0){
				clearInterval(timer);
				if(monitorType != "dep"){
					thead.append("<td>操作</td>");
					var operationColumn = {
						"data": "OPERATION",
		            	"render" : function(obj, type, full,meta) {
		            		var trendClass = "";
		            		if(monitorType == "dep"){
		            			trendClass = " trend-link";
		            		}
		            		return "<div><a class='tr' title='趋势' data-rowindex='"+meta.row+"'><i class='fa fa-line-chart"+trendClass+"'></a></i></div>";
		            	}
					}
					columns.push(operationColumn);
				}
				var tableTitle=$("#"+tabId+" #"+divId).find(".contaotalsccq").text();
				var orderDefs1=[[1,"desc"]];
				var orderDefs2=[[2,"desc"]];
				var paramsDataTables={lengthChange:false,info:false,searching:true,tableTitle:tableTitle,columnDefs:[{orderable:false,targets:[columns.length-1]}]};
				var drawCallback= function(oSettings) {
					// 获取datatables标题,供导出时获取
					oSettings.expertName = this.find(".contaotalsccq").text();
					var table = $(this);
					callback(table, oSettings);
				}
				paramsDataTables.drawCallback=drawCallback;
				if(monitorType == "dep"){
					paramsDataTables["ordering"] = false;
					paramsDataTables.paging=false;
                    paramsDataTables.searching=false ;
				}
				if(monitorType == "drgs"){
					paramsDataTables["scrollY"] = "300px";
					paramsDataTables["order"] =orderDefs2;
				}else if(monitorType == "clinic"){
					paramsDataTables["scrollY"] = "400px";
					paramsDataTables["order"] =orderDefs1;
				}
				$("#"+tabId+" #"+divId).dataTableBasic(columns,datas,paramsDataTables);
					$('.testCon').each(function(i,n){
						$(n).removeClass('testCon');
					});

			}
		}, 500);
	}
	
	// 根据指标发送请求获取数据
	function getTableData(p, quotaCode, monitorType, specHeader,callback){
		var param=jQuery.extend(true, {}, p);
		param["monitorType"]=monitorType;
		param["specHeader"]=specHeader;
		param["quotaCode"]=quotaCode;
		$.post(contextPath + "/DrgsIndexCal/indexCal.dhc",param).done(function(data){
			var data = data.data;
			callback(data, quotaCode);
		})
	}
	
	//获取双指标趋势数据
	function getTrendData(param_t, quotaCode, callback){
		param_t.quotaCode = quotaCode;
		$.post(contextPath + "/ywcHome/getCMIDRGCount.dhc",param_t).done(function(data){
			var data = data.data;
			callback(data, quotaCode);
		})
	}
	
	function loadTrendChart(title, xdata, seriesdata, legend, container){
		//调公共方法组装数据
		var lines = [];
		var echartData=[];
		for(var o in legend){
			lines.push({code:'code'+o,desc:legend[o],data:[]});
		}
		for(var o in seriesdata){
			var obj=[];
			for(var j in seriesdata[o].data){
				var temp={};
				temp.ddesc=xdata[j];
				temp['code'+o]=seriesdata[o].data[j];
				obj.push(temp);
			}
			echartData.push(obj);
		}
		var chartParams={legendPosition:'bottom'}
		lineChartBasic(container, lines, echartData, title+'变化趋势','',chartParams);
	}
	
	var ajaxc = 3;
	var drgs1, drgs2, drgs3;
	var columns = [
			{
				"data" : "ccode-ddesc",
				"fnCreatedCell" : function(nTd, sData, oData, iRow, iCol) {
					$(nTd).attr('limit', 16);
					$(nTd).limit();
				},
				"render" : function(obj, type, full) {
					return "(" + full.ccode + ")" + full.ddesc;
				}
			},
			{
				"data" : "InCaseCnt_1",
				"type" : "number-html",
				"render" : function(obj, type, full) {
					return "<a href=\"javascript:loadCaseDtl('指标("
							+ full.ddesc + ")','" + full.ccode
							+ "','drgs', 'InCaseCnt')\">"
							+ formatNumber((full["InCaseCnt"] ? full["InCaseCnt"] : ""))
							+ "</a>" + gridcompareValue(full.InCaseCnt, full.InCaseCntcc);
				}
			}, {
				"data" : "CMI"
			}, {
				"data" : "TotalWeight",
				"render": function(obj, type, full){
					return compareValue(full.TotalWeight, full.TotalWeightcc);
				}
			}, {
				"data" : "AvgDays",
				"render": function(obj, type, full){
					return compareValue(full.AvgDays, full.AvgDayscc);
				}
			}, {
				"data" : "AvgFee",
				"render": function(obj, type, full){
					return compareValue(full.AvgFee, full.AvgFeecc);
				}
			}, {
				"data" : "TotalFee",
				"render": function(obj, type, full){
					return compareValue(full.TotalFee, full.TotalFeecc);
				}
			} ];
	// 获取科室理论覆盖病组
	$.post(contextPath+"/Department/findDepDRGs.dhc", {depCode: param.pardepCode}).done(function(data){
		drgs2 = data.data;
		ajaxc--;
	});
	var p1 = drgUI.setAjaxData(tabId);//页面参数
	p1.compareType="year";
	p1.isGetCc = "1";
	getTableData(p1, "InCaseCnt,CMI,TotalWeight,AvgDays,AvgFee,TotalFee", "drgs","dep", function(data){
		drgs1 = data
		ajaxc--;
	})
	var p2 = drgUI.setAjaxData(tabId);//页面参数
	var dateFrom = addMonth(param.dateFrom, -12);
	var dateTo = addMonth(param.dateTo, -12);
	p2.dateFrom = dateFrom;
	p2.dateTo = dateTo;
	p2.isGetCc = "0";
	getTableData(p2, "InCaseCnt,CMI,TotalWeight,AvgDays,AvgFee,TotalFee", "drgs","dep", function(data){
		drgs3 = data;
		ajaxc--;
	})
	var timer_1 = setInterval(function(){
		if(ajaxc==0){
			clearInterval(timer_1);
			//病组venn图
			//drgs1--本期 drgs2--理论 drgs3--同期
			//仅本期
			var drgs1_3 = array_minus(drgs1, drgs3, "ccode"); 
			var series = [ {
				name : '本期病组',
				data : []
			}, {
				name : '理论覆盖病组',
				data : []
			}, {
				name : '同期病组',
				data : []
			} ]; 
			
			for(var i=0;i<drgs1.length;i++)
			{
				series[0].data.push(drgs1[i].ccode);
			}
			for(var i=0;i<drgs2.length;i++)
			{
				series[1].data.push(drgs2[i].ccode);
			}
			for(var i=0;i<drgs3.length;i++)
			{
				series[2].data.push(drgs3[i].ccode);
			}
			
			//标杆管理值
			$("#"+tabId+" #lineChart-3").jvenn({
				series : series,
				fnClickCallback : function() {
					// 绘制表格
					var category = "";
					for ( var i in this.listnames) {
						category += this.listnames[i]
								+ " ";
					}
					var drgCodes = [];
					for ( var i in this.list) {
						drgCodes.push(this.list[i]);
					}
					if($.inArray( "本期病组", this.listnames )>-1)
					{
						//从drgs1中过滤病组
						var tableData = drgs1.filter(function(item){
							if($.inArray(item.ccode, drgCodes)>-1)
							{return true}
						});
						loadDRGsTable(category,tableData);
						
					} else if($.inArray( "同期病组", this.listnames )>-1)
					{
						//从drgs3中过滤病组
						var tableData = drgs3.filter(function(item){
							if($.inArray(item.ccode, drgCodes)>-1)
							{return true}
						});
						loadDRGsTable(category,tableData);
						
					}
					else
					{
						//从drgs2中过滤病组
						var tableData = [];
						drgs2.forEach(function(item){
							if($.inArray(item.ccode, drgCodes)>-1)
							{
								tableData.push({"ccode":item.ccode,"ddesc":item.ddesc});
							}
						})
						loadDRGsTable(category,tableData);
					}
					
				},
				exporting: false
			})
			//默认加载表格
			loadDRGsTable('本期病组',drgs1_3);
			
			function loadDRGsTable(title,table){
				$("#"+tabId+" #drgsTable-table caption").html(title);
				var tableTitle=$("#"+tabId+" #drgsTable-table").find(".contaotalsccq").text();
				var paramsDataTables={lengthChange:false,info:false,scrollY:'350px',searching:false,order:[["1","desc"]]};
				var drawCallback= function(oSettings) {
					 var datatable = $(this);
					 var $currdt = datatable.parents(".dataChangeSel");
				}
				paramsDataTables.drawCallback=drawCallback;
				$("#"+tabId+" #drgsTable-table").dataTableBasic(columns,table,paramsDataTables);
				$("#"+tabId+" #drgsTable-table_wrapper .dataTables_scrollHeadInner table thead").before("<caption>"+title+"</caption>");
			}
		}
	})
})